package com.tian.factory;

import org.springframework.context.ApplicationContext;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * 2023年11月06日 20:25
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 * <p>
 * 获取spring bean上下文工具类
 */
public class ApplicationContextFactory {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public static <T> T getBean(String name, Class<T> type) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name, type);
    }

    public static <T> T getBean(Class<T> type) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(type);
    }

    public static Object getBeanByName(String className) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(className);
    }
}
